package ndquangr.intern.ringtonemaker;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class AllSongListActivity extends ListActivity {
	private Context m_context;
	private List<String> songTitles = new ArrayList<String>();
	private List<String> songs = new ArrayList<String>();
	private String[] MENU_ITEMS = {"Edit", "Play"};
	
	public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.all_song_list);
	        m_context = this;
	        	  
	        // Initialize items for list view
	        Bundle extras = getIntent().getExtras();
			if (extras != null) {	
				// Get specific songs base on tag
				String cate = extras.getString("category");
				String cate_detail = extras.getString("category_name");
				getSongList(cate, cate_detail);
			} else {
				// Get all songs
				getSongList();
			}
	        
	        if (songTitles != null) {
	        	ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
		        		android.R.layout.simple_list_item_1, songTitles);
	        	setListAdapter(adapter);	        	
	        }
	        ListView list = (ListView) findViewById(android.R.id.list);
	        registerForContextMenu(list);
	}	
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		//String item = (String) getListAdapter().getItem(position);
		//Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
		v.showContextMenu();
	}
	
	/** Get all songs in sd card with specific condition */
	private void getSongList(String cate, String cate_detail) {
		if (cate.equals(Constants.MUSIC_CATEGORIES[1])) {
			// Get by artist
			getByArtist(cate_detail);
		}
		else if (cate.equals(Constants.MUSIC_CATEGORIES[2])) {
			// Get by album
			getByAlbum(cate_detail);
		}
		else if (cate.equals(Constants.MUSIC_CATEGORIES[3])) {
			// Get by genre
			getByGenre(cate_detail);
		}
		else if (cate.equals(Constants.MUSIC_CATEGORIES[4])) {
			// Get by folder
			getByFolder(cate_detail);
		} 		
		else if (cate.equals(Constants.MUSIC_CATEGORIES[5])) {
			// Get by folder
			getMyFolder();
		} 		
	}

	private void getMyFolder() {
		// TODO Auto-generated method stub
		File rootFolder = new File(Environment.getExternalStorageDirectory(),Constants.ROOT_FOLDER);// "My tones");
        if (!rootFolder.exists()) {
        	rootFolder.mkdirs();
        }
        String selection = MediaStore.Audio.Media.DATA + " like " + "'%" + rootFolder.getAbsolutePath() + "%'";
		
		getSongListByCondition(selection);		
	}

	/** Get all songs in sd card in specific folder */
	private void getByFolder(String folder_name) {
		String selection = MediaStore.Audio.Media.DATA + " like " + "'%" + folder_name + "%'";
		
		getSongListByCondition(selection);		
	}

	/** Get all songs in sd card with specific genre */
	private void getByGenre(String genre_name) {
		String selection = MediaStore.Audio.Genres.NAME + " like " + "'" + genre_name + "'";
		String[] projection = {
				MediaStore.Audio.Genres._ID,
				MediaStore.Audio.Genres.NAME
		};
	
		Cursor cursor = this.managedQuery(
				MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI,
		        projection,
		        selection,
		        null,
		        null);
		String genreID = "";
		if (cursor.moveToNext()) {
			genreID = cursor.getString(0);
		}
		
		if (genreID != null && !genreID.equals("")) {
			selection = MediaStore.Audio.Genres.Members.GENRE_ID + "=" + "'" + genreID + "'";
			String[] projection_file = {
					MediaStore.Audio.Genres.Members.DATA,
			        MediaStore.Audio.Genres.Members.TITLE	
			};
			
			Uri genreuri = MediaStore.Audio.Genres.Members.getContentUri("external", Long.valueOf(genreID));
			Cursor cursor2 = this.managedQuery(
					genreuri,
			        projection_file,
			        null,
			        null,
			        MediaStore.Audio.Genres.Members.TITLE);
		
			songs = new ArrayList<String>();
			songTitles = new ArrayList<String>();
			while(cursor2.moveToNext()){
			    songs.add(cursor2.getString(0));
				songTitles.add(cursor2.getString(1));
			}
			
		}
		
	}
	
	/** Get all songs in sd card with specific album */
	private void getByAlbum(String album_name) {
		//Some audio may be explicitly marked as not being music
		String selection = MediaStore.Audio.Media.ALBUM + " like " + "'" + album_name + "'";
			
		getSongListByCondition(selection);
	}

	/** Get all songs in sd card with specific artist */
	private void getByArtist(String artist_name) {
		//Some audio may be explicitly marked as not being music
		String selection = MediaStore.Audio.Media.ARTIST + " like " + "'" + artist_name + "'";
			
		getSongListByCondition(selection);	
	}
	
	/** Get all songs in sd card */
	private void getSongList() {
		//Some audio may be explicitly marked as not being music
		//String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
	
		getSongListByCondition(null);			
	}

	/** Get all songs in sd card with specific condition in parameter */
	private void getSongListByCondition(String selection) {
		String[] projection = {
		        MediaStore.Audio.Media.DATA,
		        MediaStore.Audio.Media.TITLE	        
		};
	
		Cursor cursor = this.managedQuery(
		        MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
		        projection,
		        selection,
		        null,
		        MediaStore.Audio.Media.TITLE);
	
		songs = new ArrayList<String>();
		songTitles = new ArrayList<String>();
		while(cursor.moveToNext()){
		    songs.add(cursor.getString(0));
			songTitles.add(cursor.getString(1));
		}
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
	    ContextMenuInfo menuInfo) {
	  if (v.getId()==android.R.id.list) {
		  // AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;	    
	    
		  for (int i = 0; i<MENU_ITEMS.length; i++) {
			  menu.add(MENU_ITEMS[i]);
		  }
	  }
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
	  AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
	  Intent myIntent;
	  if (item.toString() == MENU_ITEMS[0]) {
		  myIntent = new Intent(m_context, EditAudioActivity.class);		
		  myIntent.putExtra("uri", songs.get(info.position));
		  startActivity(myIntent);
	  } else if (item.toString() == MENU_ITEMS[1]) {
		  myIntent = new Intent(m_context, MusicPlayerActivity.class);		
		  myIntent.putExtra("uri", songs.get(info.position));
		  startActivity(myIntent);
	  }
	  return true;
	}
}
